package org.cytoscape.myapp.cytoscape_app_v1.internal.tasks;

import java.util.List;

import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.group.CyGroup;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.subnetwork.CyRootNetwork;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskMonitor;

public class CreateSubnetworkTask implements Task{

	
	private CyApplicationManager applicationManger;
	private CyGroupManager groupManager;
	private CyNetworkManager networkManager;
	private CyNetworkViewManager networkViewManager;
	private CyNetworkViewFactory networkViewFactory;
	private CyRootNetworkManager netRootNetworkManager;
	private CyNode node;
	
	public CreateSubnetworkTask(CyApplicationManager applicationManger,CyGroupManager groupManager,
									CyNetworkManager networkManager, CyNetworkViewManager networkViewManager, 
										CyNetworkViewFactory networkViewFactory, CyRootNetworkManager netRootNetworkManager){
		this.applicationManger = applicationManger;
		this.groupManager = groupManager;
		this.networkManager = networkManager;
		this.networkViewFactory = networkViewFactory;
		this.networkViewManager = networkViewManager;
		this.netRootNetworkManager = netRootNetworkManager;
		
	}
	
	public void setNodeParent(Long suid){
		this.node = applicationManger.getCurrentNetwork().getNode(suid);
	}
	
	@Override
	public void run(TaskMonitor taskMonitor) throws Exception {
		CyRootNetwork netRoot = netRootNetworkManager.getRootNetwork(applicationManger.getCurrentNetwork());

		CyGroup grupo =groupManager.getGroup(node, applicationManger.getCurrentNetwork());
		
		List<CyEdge> edges = grupo.getInternalEdgeList();
		List<CyNode> nodes = grupo.getNodeList();

		CySubNetwork subNet = netRoot.addSubNetwork();
		subNet.getRow(subNet).set(CyNetwork.NAME,applicationManger.getCurrentNetwork().getDefaultNodeTable().getRow(grupo.getGroupNode().getSUID()).get("name", String.class) );
			
		for(CyNode node:nodes){
			 subNet.addNode(node);
		}
		
		for(CyEdge edge:edges){
			subNet.addEdge(edge);
		}
		
		networkManager.addNetwork(subNet);
		CyNetworkView viewNew = networkViewFactory.createNetworkView(subNet);
		networkViewManager.addNetworkView(viewNew);
		applicationManger.setCurrentNetwork(subNet);
	}
		
	

	@Override
	public void cancel() {
		// TODO Auto-generated method stub
		
	}

}
